# coding:utf-8

import warnings

warnings.simplefilter('ignore', DeprecationWarning)
import pymysql
from common.log import Log
import logging
from config import DATABASE

Log()


class MYSQL(object):

    def __init__(self):
        self.host = DATABASE["host"]
        self.user = DATABASE["user"]
        self.password = DATABASE["password"]
        self.database = DATABASE["database"]
        self.charset = DATABASE["charset"]
        self.port = DATABASE["port"]
        try:
            logging.debug("正在连接数据库..")
            self.conn = pymysql.connect(host=self.host, user=self.user, password=self.password, database=self.database,
                                        port=self.port, charset=self.charset)
        except Exception as e:
            raise e

    def connect_database(self):
        """
        连接数据库
        :return:
        """
        try:

            # 查看连接是否成功
            cursor = self.conn.cursor(cursor=pymysql.cursors.DictCursor)
            logging.debug("数据库连接成功..")
            return cursor
        except Exception as e:
            logging.error("连接数据库失败..{}".format(e))
            raise e

    def run_sql(self, sql):
        """
        执行sql语句
        :param sql:
        :return:
        """
        try:
            logging.debug("准备执行SQL语句..")
            cursor = self.connect_database()
            cursor.execute(sql)
            rs = cursor.fetchall()
            return rs
        except Exception as e:
            logging.error("执行SQL失败..{}".format(e))
            raise

    def commit(self):
        self.conn.commit()


if __name__ == "__main__":
    DB = MYSQL()
    datas = DB.run_sql("select * from device where region_id is null and category_id='{}' limit 20".format(
        'F000'))

    print(datas)
